package com.stylefeng.guns.modular.train.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.persistence.model.ContestPoints;
import com.stylefeng.guns.common.constant.MvcResult;
import com.stylefeng.guns.common.persistence.model.Employee;
import com.stylefeng.guns.config.excel.ExcelExportStylerImpl;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.util.BeanUtils;
import com.stylefeng.guns.modular.system.service.IDictService;
import com.stylefeng.guns.modular.system.service.IQualityGradeRuleService;
import com.stylefeng.guns.modular.train.service.IEmployeeService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.common.persistence.model.DegreeTrainPoints;
import com.stylefeng.guns.modular.train.service.IDegreeTrainPointsService;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.stylefeng.guns.common.constant.Const;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * 学历提升积分控制器
 *
 * @author fengshuonan
 * @Date 2018-01-28 15:04:43
 */
@Controller
@RequestMapping("/degreeTrainPoints")
public class DegreeTrainPointsController extends BaseController {

    private String PREFIX = "/train/degreeTrainPoints/";

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDegreeTrainPointsService degreeTrainPointsService;

    @Autowired
    private IQualityGradeRuleService qualityGradeRuleService;

    @Autowired
    private IDictService dictService;

    private static List<DegreeTrainPoints> REPEAT = new ArrayList<>();

    /**
     * 跳转到学历提升积分首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "degreeTrainPoints.html";
    }

    /**
     * 跳转到添加学历提升积分
     */
    @RequestMapping("/degreeTrainPoints_add")
    public String degreeTrainPointsAdd(Model model) {
        model.addAttribute("educations", qualityGradeRuleService.getByGradeType(Const.DEGREE_TRAIN));
        model.addAttribute("degrees", dictService.getByPCode("degree"));
        model.addAttribute("learnTypes", dictService.getByPCode("learn_type"));
        return PREFIX + "degreeTrainPoints_add.html";
    }

    /**
     * 跳转到修改学历提升积分
     */
    @RequestMapping("/degreeTrainPoints_update/{degreeTrainPointsId}")
    public String degreeTrainPointsUpdate(@PathVariable String degreeTrainPointsId, Model model) {
        DegreeTrainPoints degreeTrainPoints = degreeTrainPointsService.selectById(degreeTrainPointsId);
        model.addAttribute("item",degreeTrainPoints);
        model.addAttribute("educations", qualityGradeRuleService.getByGradeType(Const.DEGREE_TRAIN));
        model.addAttribute("degrees", dictService.getByPCode("degree"));
        model.addAttribute("learnTypes", dictService.getByPCode("learn_type"));
        LogObjectHolder.me().set(degreeTrainPoints);
        return PREFIX + "degreeTrainPoints_edit.html";
    }

    /**
     * 获取学历提升积分列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Employee employee, Double min, Double max) {

        if(BeanUtils.checkFieldValueNull(employee) && min == null && max == null){
            List<DegreeTrainPoints> degreeTrainPointss = degreeTrainPointsService.selectList(null);
            degreeTrainPointss.forEach(n ->{
                if(n.getGraduationDate() != null){
                    n.setStrGraduationDate(Const.df.format(n.getGraduationDate()));
                    n.setStrEnrolDate(Const.df.format(n.getEnrolDate()));
                }
            });
            return degreeTrainPointss;
        }

        EntityWrapper<Employee> wrapper = new EntityWrapper<>();
        wrapper.setEntity(employee);
        List<Employee> employees = employeeService.selectList(wrapper);
        Set<String> empCodes = new HashSet<>();
        employees.forEach(e -> empCodes.add(e.getEmpCode()));

        List<DegreeTrainPoints> networkTrainPointss = new ArrayList<>();

        if(!empCodes.isEmpty()){
            EntityWrapper<DegreeTrainPoints> nwWrapper = new EntityWrapper<>();
            nwWrapper.in("emp_code",empCodes);

            if(min != null || max != null){
                min = min == null ? 0.0 : min;
                max = max == null ? 9999.0 : max;

                nwWrapper.between("integral",min,max);
            }

            networkTrainPointss = degreeTrainPointsService.selectList(nwWrapper);


        }
        networkTrainPointss.forEach(n ->{
            if(n.getGraduationDate() != null) {
                n.setStrGraduationDate(Const.df.format(n.getGraduationDate()));
                n.setStrEnrolDate(Const.df.format(n.getEnrolDate()));
            }
        });
        return networkTrainPointss;
    }
    /**
     * 新增学历提升积分
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(DegreeTrainPoints degreeTrainPoints) {
        degreeTrainPoints.setDataOrigin(Const.IMPORT_TYPE_SYS);
        degreeTrainPoints.setCreateDate(new Date());
        degreeTrainPointsService.insert(degreeTrainPoints);
        return super.SUCCESS_TIP;
    }


    @RequestMapping(value = "/adds")
    @ResponseBody
    public Object adds(@RequestBody DegreeTrainPoints[] repeatData) {
        List<DegreeTrainPoints> degreeTrainPointss = Arrays.asList(repeatData);
        batchFillObj(degreeTrainPointss);
        degreeTrainPointsService.insertBatch(degreeTrainPointss);

        return super.SUCCESS_TIP;
    }
    /**
     * 删除学历提升积分
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam String degreeTrainPointsId) {
        if(degreeTrainPointsId.contains(",")){
            List<String> ids = Arrays.asList(degreeTrainPointsId.split(","));
            degreeTrainPointsService.deleteBatchIds(ids);
        }else{
            degreeTrainPointsService.deleteById(degreeTrainPointsId);
        }
        return SUCCESS_TIP;
    }

    /**
     * 修改学历提升积分
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(DegreeTrainPoints degreeTrainPoints) {
        degreeTrainPointsService.updateById(degreeTrainPoints);
        return super.SUCCESS_TIP;
    }

    /**
     * 学历提升积分详情
     */
    @RequestMapping(value = "/detail/{degreeTrainPointsId}")
    @ResponseBody
    public Object detail(@PathVariable("degreeTrainPointsId") String degreeTrainPointsId) {
        return degreeTrainPointsService.selectById(degreeTrainPointsId);
    }


    /**
     * 跳转到导入学历提升积分
     */
    @RequestMapping("/degreeTrainPoints_import")
    public String degreeTrainPointsImport() {
        return PREFIX + "degreeTrainPoints_import.html";
    }

    /**
     * 导入学历提升积分
     */
    @RequestMapping(value = "/import")
    @ResponseBody
    public Object imports(MultipartHttpServletRequest mutReq) {

        ImportParams params = new ImportParams();
        params.setStartRows(0);
        params.setTitleRows(1);

        int count = 2;
        try {
            List<DegreeTrainPoints> degreeTrainPointss = ExcelImportUtil.importExcel(mutReq.getFile("file").getInputStream(), DegreeTrainPoints.class, params);
            Date now = new Date();

            Map<String, String> nameAndCode = employeeService.getNameAndCode();
            List<DegreeTrainPoints> noRepeat = new ArrayList<>();
            List<DegreeTrainPoints> hasCodeList = new ArrayList<>();
            //字典
            Map<String, String> learnTypes = dictService.getMapNameNumByPcode("learn_type");
            Map<String, String> degrees = dictService.getMapNameNumByPcode("degree");

            Map<String, String> xueweis = qualityGradeRuleService.getMapGradeAndGradeCodeByType(Const.DEGREE_TRAIN);
            Map<String, Double> points = qualityGradeRuleService.getMapGradeCodeAndIntegralByType(Const.DEGREE_TRAIN);


            for (DegreeTrainPoints degreeTrainPoints : degreeTrainPointss) {
                degreeTrainPoints.setDataOrigin(Const.IMPORT_TYPE_XML);
                degreeTrainPoints.setCreateDate(now);


                if(StringUtils.isEmpty(degreeTrainPoints.getEmpCode())) {
                    //姓名检测
                    if (nameAndCode.containsKey(degreeTrainPoints.getEmpName())) {
                        //有该姓名，检测是否重名
                        if (nameAndCode.get(degreeTrainPoints.getEmpName()).contains(",")) {
                            //有重名情况
                            degreeTrainPoints.setEmpCode(Const.DEFAULT_CODE);
                            REPEAT.add(degreeTrainPoints);
                        } else {
                            //无重名、正常插入
                            degreeTrainPoints.setEmpCode(nameAndCode.get(degreeTrainPoints.getEmpName()));

                            degreeTrainPoints.setDegreeCode(degrees.get(degreeTrainPoints.getDegree()));
                            degreeTrainPoints.setLearnTypeCode(learnTypes.get(degreeTrainPoints.getLearnType()));
                            degreeTrainPoints.setEducationCode(xueweis.get(degreeTrainPoints.getEducation()));
                            if(!StringUtils.isEmpty(degreeTrainPoints.getEducationCode())){
                                degreeTrainPoints.setIntegral(points.get(degreeTrainPoints.getEducationCode()));
                            }else {
                                degreeTrainPoints.setIntegral(0.0);
                            }
                            noRepeat.add(degreeTrainPoints);
                        }
                    } else {
                        throw new Exception("姓名为 " + degreeTrainPoints.getEmpName() + " 在员工管理中不存在!");
                    }
                }else{
                    degreeTrainPoints.setDegreeCode(degrees.get(degreeTrainPoints.getDegree()));
                    degreeTrainPoints.setLearnTypeCode(learnTypes.get(degreeTrainPoints.getLearnType()));
                    degreeTrainPoints.setEducationCode(xueweis.get(degreeTrainPoints.getEducation()));
                    if(!StringUtils.isEmpty(degreeTrainPoints.getEducationCode())){
                        degreeTrainPoints.setIntegral(points.get(degreeTrainPoints.getEducationCode()));
                    }else {
                        degreeTrainPoints.setIntegral(0.0);
                    }
                    hasCodeList.add(degreeTrainPoints);
                }

                count++;
            }

            //不重复，先插入
            if(noRepeat.size() > 0){
                degreeTrainPointsService.insertBatch(noRepeat);
            }
            if(hasCodeList.size() > 0){
                degreeTrainPointsService.insertBatch(hasCodeList);
            }
            //处理重复数据
            if(!REPEAT.isEmpty()){
                MvcResult mvcResult = new MvcResult();
                mvcResult.setData(REPEAT);

                return mvcResult;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorTip(400,"第"+ count+"条 " +e.getMessage());
        }

        SuccessTip successTip = super.SUCCESS_TIP;
        successTip.setMessage(String.format("成功插入%d", count-2)  + "条数据");
        return successTip;
    }

    @RequestMapping("/repeat")
    public String repeat(Model model){
        model.addAttribute("repeat", JSON.toJSONString(REPEAT));

        //消费后清空
        REPEAT = new ArrayList<>();
        return PREFIX + "repeat.html";
    }

    public void batchFillObj(List<DegreeTrainPoints> degreeTrainPointss) {
        Date now = new Date();
        //字典
        Map<String, String> learnTypes = dictService.getMapNameNumByPcode("learn_type");
        Map<String, String> degrees = dictService.getMapNameNumByPcode("degree");

        Map<String, String> xueweis = qualityGradeRuleService.getMapGradeAndGradeCodeByType(Const.DEGREE_TRAIN);
        Map<String, Double> points = qualityGradeRuleService.getMapGradeCodeAndIntegralByType(Const.DEGREE_TRAIN);

        degreeTrainPointss.forEach(degreeTrainPoints -> {
            degreeTrainPoints.setDataOrigin(Const.IMPORT_TYPE_XML);
            degreeTrainPoints.setCreateDate(now);
            degreeTrainPoints.setDegreeCode(degrees.get(degreeTrainPoints.getDegree()));
            degreeTrainPoints.setLearnTypeCode(learnTypes.get(degreeTrainPoints.getLearnType()));
            degreeTrainPoints.setEducationCode(xueweis.get(degreeTrainPoints.getEducation()));
            if(!StringUtils.isEmpty(degreeTrainPoints.getEducationCode())){
                degreeTrainPoints.setIntegral(points.get(degreeTrainPoints.getEducationCode()));
            }else {
                degreeTrainPoints.setIntegral(0.0);
            }
        });
    }
    /**
     * 导出
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<DegreeTrainPoints> degreeTrainPoints= degreeTrainPointsService.selectList(null);
            ExportParams exportParams=new ExportParams("学历提升积分统计表", "学历提升积分统计表");
            exportParams.setStyle(ExcelExportStylerImpl.class);
            exportParams.setTitleHeight((short)14);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, DegreeTrainPoints.class, degreeTrainPoints);
            OutputStream outputStream=response.getOutputStream();
            String fileName="学历提升积分统计表.xls";
            response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO-8859-1"));
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
